<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>
    <van-list
      v-model="loading"
      :finished="done"
      finished-text="没有数据啦！"
      @load="pullUpLoadMoreFn"
      :immediate-check="false"
      offset="50"
    >
      <!-- 文章列表组件 -->
      <article-list :list="resultList" :showCross="false" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResultListAPI } from '@/api/Search'
export default {
  name: 'ResultList',
  data () {
    return {
      resultList: [], // 搜索结果列表
      loading: false, // 控制上拉每一页的加载状态
      done: false // 控制整个列表的加载状态
    }
  },
  activated () {
    // 初始页码
    // 每次组件被激活时，把状态重置为初始状态
    this.page = 1
    this.resultList = []
    this.loading = false
    this.done = false
    // 发请求
    this.getSearchResultList()
  },
  methods: {
    // 获取搜索结果
    async getSearchResultList () {
      // 调接口
      const resp = await getSearchResultListAPI({
        keyword: this.$route.params.keyword,
        page: this.page++
      })
      const { results } = resp.data
      // 加载结束的判断
      if (results.length === 0) {
        this.done = true
        return
      }
      // 数组合并
      this.resultList = [...this.resultList, ...results]
      this.loading = false
    },
    // 上拉触底加载更多
    pullUpLoadMoreFn () {
      this.getSearchResultList()
    }
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
